package com.other.thread.energy;

public class EnergySystem {
	
	private final double[] energyBoxes;//能量存放的地方
	
	private final Object lockObj = new Object();
	
	public EnergySystem(int n,double initialEnergy){
		energyBoxes = new double[n];
		for (int i = 0; i < energyBoxes.length; i++) {
			energyBoxes[i] = initialEnergy;
		}
	}
	
	/**
	 * 能量转移
	 * @param from 源头
	 * @param to 终点
	 * @param amount 能量值
	 */
	public void transfer(int from,int to,double amount){
		synchronized (lockObj) {
			//while循环，保证条件不满足时任务都会被条件阻挡
			 //而不是继续竞争CPU资源
			 while(energyBoxes[from] < amount){
				try {
					//条件不满足, 将当前线程放入Wait Set
					lockObj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				return;
			}
			
			System.out.println(Thread.currentThread().getName());
			energyBoxes[from] -= amount;
			System.out.printf("从%d转移%10.2f单位能量到%d",from,amount,to);
			energyBoxes[to] += amount;
			System.out.printf("能量总和%10.2f%n",getTotalEnergy());
			//唤醒所有在lockObj对象上等待的线程
			lockObj.notifyAll();
		}
		
	}
	
	
	public double getTotalEnergy(){
		double sum = 0;
		for (int i = 0; i < energyBoxes.length; i++) {
			sum += energyBoxes[i];
		}
		return sum;
	}
	
	public int getBoxAmount(){
		return energyBoxes.length;
	}
}
